#!/usr/bin/python
#coding:utf-8
'''
基于随机森林的特征选择
'''
import numpy as np
np.set_printoptions(threshold=np.inf)

from sklearn.ensemble import RandomForestClassifier #随机森林
import matplotlib.pyplot as plt

import pandas

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题


def ForestClassifierClass():
    '''
    随机森林筛选特征 
    '''
    txturl='E:/python-space/eci/anomalyDetection/model.txt';
    dataframe = pandas.read_csv(txturl,header=0) #sep=",",skiprows=0
    #获取特征名
    names= dataframe.columns
    names = np.array(names,dtype=np.str) 

    data = dataframe.values
    print(data.shape)

    X=data[:,0:51]
    y = data[:,51] 
    feature_num=10;
    result=[]
    for i in range(10):                           #这里我们进行十次循环取交集
        rfc = RandomForestClassifier(n_jobs=-1)
        rfc.fit(X, y)
        # print("training finished")
        importances = rfc.feature_importances_    #特征重要程度
        # print(importances)
        indices = np.argsort(importances)[::-1]   # 降序排列  返回数据的排序下标
        feature={}
        num=1;
        for f in range(X.shape[1]):
            if f < feature_num:                          #选出前50个重要的特征
                # print(names[indices[f]])
                feature[names[indices[f]]]=num;
                num=num+1;
                
        result.append(feature)
       
    # for i in range(len(result)):
    #     print(result[i])
    showLabels(result)

def showLabels(result):
    '''
    图形化显示标签
    '''

    feature_num={}
    for i in range(len(result)):
        for name in (result[i]):  
            if name in feature_num:
                list=feature_num[name]
                list+=1;
                feature_num[name]=list
            else:
                list=1
                feature_num[name]=list
    
    print(feature_num) #特征名和个数

    feature_name=[]   #特征名
    for i in range(len(result)):
        for name in (result[i]):
            if name not in feature_name:
                feature_name.append(name)

    labelsDict=[]  #列数值
    for i in range(len(result)):
        data=[]
        for num in range(len(feature_name)):
            state=0
            for name in (result[i]):
                if feature_name[num] == name:
                    data.append(result[i][name])
                    state=1
            if state==0 :
                data.append(0)
        labelsDict.append(data)
    
    x=np.arange(len(feature_name))
    width=0.5
    fig,ax=plt.subplots()
    c1="#99CCFF"
    c2="#CCFFFF"
    c3="#6699CC"
    value=0
    for i in range(len(labelsDict)):
        if i==0:
            ax.bar(x,labelsDict[i],width,color=c1,edgecolor='r')
            value=np.array(labelsDict[i])
        else:
            if i % 2 == 0:   
                ax.bar(x,labelsDict[i],width,value,color=c2,edgecolor='g')
                value=value+np.array(labelsDict[i])
            elif i%3==0:
                ax.bar(x,labelsDict[i],width,value,color=c3,edgecolor='b')
                value=value+np.array(labelsDict[i])
            else:
                ax.bar(x,labelsDict[i],width,value,color=c1,edgecolor='r')
                value=value+np.array(labelsDict[i])

    ax.set_xticks(x)
    ax.set_xticklabels(feature_name)
    plt.show()
   

def main():
    ForestClassifierClass()

if __name__ == '__main__':
    main()